package handler

import (
	"encoding/json"
	"info-sys/cache"
	"info-sys/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.PostForm("page"))
	size, _ := strconv.Atoi(c.PostForm("size"))
	offset := (page - 1) * size

	var post []model.Post

	redis_list_key := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Offset(offset).Limit(size).Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &post)
	}

	var total int64
	model.DB.Model(&model.Post{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表成功",
		"data":  post,
		"total": total,
	})
	return

}
